package com.lyj.ui.servlet;

import java.io.IOException;

import javax.management.RuntimeErrorException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lyj.pojo.User;
import com.lyj.service.SubjectService;
import com.lyj.service.UserService;
import com.lyj.service.impl.SubjectServiceImpl;
import com.lyj.service.impl.UserServiceImpl;
import com.lyj.util.RuleException;

@WebServlet("/DoLoginServlet")
public class DoLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		//获取浏览器提交的数据
		String name = request.getParameter("name");
		String pwd = request.getParameter("pwd");
		String remember = request.getParameter("remember");
		//实体类对象作为数据载体
		User user = new User();
		user.setName(name);
		user.setPwd(pwd);
		user.setRemember(remember);
		
		UserService userService = new UserServiceImpl();
		try {
			user = userService.login(user);
			request.getSession().setAttribute(User.SESSION_NAME, user);
			//写Cookie
			if(remember != null) {
				Cookie cookie = new Cookie(User.SESSION_NAME, user.getId().toString());
				cookie.setMaxAge(10*24*60*60);
				response.addCookie(cookie);
			}
			//衔接jsp,跳转到进入登录时的地址，默认为首页
			//request.getHeader("refere");
//			response.sendRedirect(request.getContextPath() + "/list");

			request.getRequestDispatcher("/ListServlet").forward(request, response);
		}catch (RuleException re) {
			request.setAttribute("user", user);
			request.setAttribute("message", re.getMessage());
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
		} catch (Exception e) {
			//交给全局的异常处理过滤器
			throw new RuntimeException(e);
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
